<?php
/**
 * Created by JetBrains PhpStorm.
 * User: joedarkangel3
 * Date: 8/29/11
 * Time: 5:04 PM
 * To change this template use File | Settings | File Templates.
 */
 
class category_relation extends CI_Controller {
	/**
	 * load common models and save them to $this without model suffix
	 */
	function __construct()
	{
		parent::__construct();
		$this->load->model('food_category_model', 'food_category');
		$this->load->model('food_option_category_model', 'food_option_category');
        $this->load->model('category_relation_model', 'category_relation');
        $this->load->library('session');
	}

    function index()
    {
        $food_category = $this->food_category->get_category();
        $food_option_category = $this->food_option_category->get_category();

        // remove option category that is in 'all' scope
        $temp_option_cat = array();
        foreach($food_option_category as $foc) {
            if($foc['scope'] == 'quick')
                $temp_option_cat[] = $foc;
        }
        $food_option_category = $temp_option_cat;
        // -------------------------------------------------

        $food_select = (int)$this->input->post('food_select');

        if($food_select == 0)
        {
            $first_category = current($food_category);
            $food_select = $first_category['id'];
        }

        $opt_select = $this->category_relation->read($food_select);

        if(count($opt_select)  === 0)
        {
            $opt_select = -1;
        }

        $data = array(
            'food_category' => $food_category,
            'food_option_category' => $food_option_category,
            'food_select' => $food_select,
            'opt_select' => $opt_select['food_option_category_id'],
            'page_title' => 'food item',
            'page_css' => array('admin.css'),
            'page_js' => array()
        );

        $this->load->view('admin/category_relation', $data);
    }

    function change_relation(){
        $food_category_id = $this->input->post('food_category_id');
        $option_category_id = $this->input->post('option_category_id');

        // now determine which action to take
        $had_relation = '';
        $current_option_id = $this->category_relation->read($food_category_id);
        count($current_option_id) == 2 ? $had_relation = true : $had_relation = false;

        if($option_category_id == -1){
            if($had_relation)
                $this->category_relation->delete($food_category_id);
        }
        else{
            if($had_relation)
                $this->category_relation->update($food_category_id, $option_category_id);
            else
                $this->category_relation->create($food_category_id, $option_category_id);
        }
    }
}